package com.hghivln.blog.common.upload;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hghivln.blog.common.exception.BlogException;
import com.hghivln.blog.pojo.vo.UploadVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Component
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    @Autowired
    private UploadProperties prop;

    @Autowired
    private FastFileStorageClient storageClient;

    public UploadVo uploadImage(MultipartFile file) {
        // 1.检验文件类型
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new BlogException("文件类型不支持！");
        }
        // 2.检验文件内容
        assert contentType != null;
        String[] split = contentType.split("/");
        System.out.println(split[0]);
        if (split[0].equals("image")){
            try {
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image == null || image.getWidth() == 0 || image.getHeight() == 0){
                    throw new BlogException("上传的文件内容有问题！");
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new BlogException("校验文件内容失败....{}",e);
            }
        }

        // 3.上传到FastDFS
        try {
            // 获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 获取文件名字
            String fileName = StringUtils.substringBeforeLast(file.getOriginalFilename(), ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路径
            String path = prop.getBaseUrl() + storePath.getFullPath();
            return new UploadVo(path, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BlogException("【文件上传】上传文件失败！....{}",e);
        }
    }
}
